import 'dart:async';

import 'package:connectivity/connectivity.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:sqflite/sqflite.dart';
import 'package:ymt/api/apis.dart';
import 'package:ymt/db/offline_database_provider.dart';
import 'package:ymt/model/product.dart';
import 'package:ymt/model/product/detail.dart';
import 'package:ymt/ui/screen.dart';
import 'package:ymt/utils/image.dart';
import 'package:ymt/utils/request.dart';

class DetailsPage extends StatefulWidget{

  final List<Product> _products;
  final int _page;

  final _pageContext;

  DetailsPage(this._products, this._page, this._pageContext);

  @override
  State<StatefulWidget> createState() {
    return _DetailsPageState(this._pageContext, _products,_page);
  }
}

/// 1.分页加载；2.indicator；3.请求失败调用离线数据
class _DetailsPageState  extends State<DetailsPage>{
  final List<Product> _products;
  int _page;
  ProductDetail _currentDetail;
  bool _hiden = false;
  Screen _screen;
  bool _loadOffline = false;
  Database db;

  var _currentImagePage = 0;
  var _productTotal = 1;

  Dio dio;

  bool _autoplay = false;
  PageController _pageController;
  Timer _timer;
  Map<int, ProductDetail> imagesOfProducts = Map();
  var _pageContext;

  _DetailsPageState(this._pageContext, this._products, this._page);

  @override
  void initState() {
    initData();
    executeTask();
    super.initState();
  }

  initData(){
    _pageController = PageController(initialPage: _page);
  }

  executeTask() async {
    _productTotal = _products.length;
    var currentProduct = _products[_page];
    var connectivityResult = await Connectivity().checkConnectivity();
    print(connectivityResult);
    if (connectivityResult == ConnectivityResult.none) {
      _loadOffline = true;
    }else{
      _loadOffline = false;
      initDio();
    }
    _requestProductAndSetState(currentProduct);
  }

  void initDio(){
    dio = Request.dio();
  }

  @override
  Widget build(BuildContext context) {
    var currentProduct = _products[_page];
    Widget background = _buildBackStack(_buildPageView());

    Widget productIndicator = _buildIndicators(_page, _productTotal);
    List<Widget> stacks = [Stack(alignment: AlignmentDirectional.topEnd,
      children: <Widget>[background, productIndicator],),];
    var currentDetail = currentProduct.detail;
    if(currentDetail != null){
      _screen = Screen(_pageContext, currentProduct, currentDetail, (){
        setState(() {
          _hiden = false;
          _autoplay = true;
        });
        if(_pageController != null) {
          _timer = Timer.periodic(Duration(seconds: 3), (timer){
            var page;
            if (_page == _productTotal - 1) {
              page = _page = 0;
            }else{
              page = _page + 1;
            }
            print(page);
            _pageController.animateToPage(page, duration: const Duration(seconds: 2),curve: Curves.fastOutSlowIn);
          });
        }
        print("轮播");
      });
      Widget clickWidget = GestureDetector(child: _screen, onTap: () {
        setState(() {
          _hiden = !_hiden;
        });
      },);
      Widget halfBackground = Container(child: clickWidget,decoration: BoxDecoration(color: Color(0xaf000000)),);
      Widget foreground = _buildHidenableWidget(halfBackground);
      stacks.add(foreground);
    }
    return Stack(children: stacks);
  }

  Widget _buildBackStack(content){
    var back = click(Container(
      child: Icon(Icons.arrow_back_ios),
      margin: EdgeInsets.only(left: 15, top: 30),
      padding: EdgeInsets.all(10),
      decoration: BoxDecoration(shape: BoxShape.circle,
          border: Border.all(color: Colors.white,)),), ()=>Navigator.pop(_pageContext));
    return Stack(children: <Widget>[content, back],alignment: AlignmentDirectional.topStart,);
  }

  Widget click(child, onTap) {
    return GestureDetector(child: child, onTap: onTap,);
  }

  Widget _buildHidenableWidget(child){
    return Visibility(visible: _hiden,child: child,);
  }

  Widget _buildHorizontalSwiper(autoplay){
    return Swiper(
      itemBuilder: (context, position) {
        var currentProduct = _products[position];
        List<String> images = List();
        images.add(currentProduct.main_picture_big);
        if(currentProduct.detail != null) {
          images.addAll(currentProduct.detail.images);
        }
        return _buildVerticalSwiper(images);
      },
      scrollDirection: Axis.horizontal,
      itemCount: _products.length,
      index: _page,
      loop: true,
      autoplay: autoplay,
      onIndexChanged: (int index) {
        _changeProduct(index);
      },);
  }

  Widget _buildPageView(){//重复数据问题。。。
    return PageView.builder(itemBuilder: (context, position) {
      var currentProduct = _products[position];
      List<String> images = List();
      images.add(currentProduct.main_picture_big);
      if(currentProduct.detail != null){
        images.addAll(currentProduct.detail.images);
      }
      return _buildVerticalSwiper(images);
    },scrollDirection: Axis.horizontal,itemCount: _products.length,onPageChanged: (int index) {
      _changeProduct(index);
    },controller: _pageController,);
  }


  Widget _buildIndicators(page,total){
    return Container(
      alignment: Alignment.center,
      margin: EdgeInsets.all(20),
      color: Colors.black54,
      width: 50,
      height: 25,
      child: Text("${page + 1}/$total",
        style: TextStyle(fontSize: 14, color: Colors.white),),);
  }

  _changeProduct(index){
    print("切换$index");
    setState(() {
      _currentImagePage = 0;
      _page = index;//切换回之前的产品，图片序列会恢复第一张
    });
    _requestProduct(_products[_page]);
  }

  Widget _buildVerticalSwiper(List<String> images){
    Widget imageIndicator = _buildIndicators(_currentImagePage, images.length);
    Widget swiper =  Swiper(scrollDirection: Axis.vertical,itemBuilder: (context, position){
      // FadeInImage
      return CacheImage.loadImageWithFit(images[position], BoxFit.fitWidth);
    },itemCount: images.length,onTap: (int index){
      if(_timer != null){
        _timer.cancel();
      }
      setState(() {
        _hiden = !_hiden;
      });
    },loop: false,onIndexChanged: (index){
      setState(() {
        _currentImagePage = index;
      });
    },);
    return Stack(alignment: AlignmentDirectional.bottomCenter,children: <Widget>[swiper, imageIndicator],);;
  }


  _requestProduct(Product product) async {
    if(_loadOffline) {
      await OfflineDatabaseProvider().open((database) async {
        //先保证数据库得以运行
        db = database;
        List<Map> maps = await db.query(
            OfflineDatabaseProvider.TABLE_PICTURES, where: "product_id = ?",
            whereArgs: [product.id]);
        List<String> images = List();
        maps.forEach((item) {
          images.add("${ApiCenter.IMAGE_HOST}/${product.id}/${item["file"]}");
        });
        ProductDetail _currentDetail = ProductDetail();
        _currentDetail.id = product.id;
        _currentDetail.main_picture = product.main_picture;
        _currentDetail.images = images;
        product.detail = _currentDetail;
        update;
      });
    }else{
      Response response = await dio.get(ApiPaths.PRODUCT, queryParameters: {"id": product.id});
      ProductDetail _currentDetail = ProductDetail.fromJson(response.data);
      product.detail = _currentDetail;
      update();
    }
  }

  _requestProductAndSetState(Product product) async {
    if(_loadOffline){
      await OfflineDatabaseProvider().open((database) async {
        //先保证数据库得以运行
        db = database;
        List<Map> maps = await db.query(OfflineDatabaseProvider.TABLE_PICTURES, where: "product_id = ?", whereArgs: [product.id]);
        List<String> images = List();
        maps.forEach((item){
          images.add("${ApiCenter.IMAGE_HOST}/${item["id"]}/${item["file"]}");
        });
        ProductDetail _currentDetail = ProductDetail();
        _currentDetail.id = product.id;
        _currentDetail.main_picture = product.main_picture;
        _currentDetail.images = images;
        product.detail = _currentDetail;
        update();
      });
    }else{
      Response response = await dio.get(ApiPaths.PRODUCT, queryParameters: {"id": product.id});;
      ProductDetail _currentDetail = ProductDetail.fromJson(response.data);
      product.detail = _currentDetail;
      update();
    }
  }

  update(){
    if(mounted){
      setState(() {});
    }
  }

  @override
  void dispose() {
    if(_timer != null) {
      _timer.cancel();
    }
    print("dispose");
    super.dispose();
  }
}